package com.example.bigevent.Interceptors;

import com.example.bigevent.utills.ThreadLocalUtil;
import org.springframework.web.servlet.HandlerInterceptor;

/*这个一个拦截器*/
import com.example.bigevent.pojo.Result;
import com.example.bigevent.utills.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;
@Component
/*@Component是 Spring 框架中用于标识一个 Java 类是一个组件的注解。它是 Spring 进行组件扫描和自动装配的基础
，被标注为@Component的类会被 Spring
容器识别并进行管理，使得这些类可以方便地参与到 Spring 框架的各种功能中，*/
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //令牌验证
        String token = request.getHeader("Authorization");
        try {
            Map<String, Object> claims = JwtUtil.parseToken(token);//出错了就说明

            //把业务数据存储到ThreadLocal中
            ThreadLocalUtil.set(claims);
            //放行
            return true;
        } catch (Exception e) {
            response.setStatus(401);
            //不放行
            return false;
        }

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
        //清空ThreadLocal中的数据
        ThreadLocalUtil.remove();
    }
}
